<template>
  <div>
    <!-- 搜索组件一级路由   $router.back()返回上一个页面-->
    <van-nav-bar
      left-arrow
      title="搜索中心"
      @click-left="$router.back()"
    ></van-nav-bar>
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @search="onSearch"
      @input="fangdou"
    >
      <div slot="action" @click="Hsearch">搜索</div>
    </van-search>

    <!-- 联想建议 -->
    <van-cell-group v-show="keyword">
      <van-cell v-for="(item, index) in cSuggestion" :key="index" icon="search">
        <div v-html="item" @click="Hsuggestion(index)"></div>
      </van-cell>
    </van-cell-group>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <van-cell-group v-show="!keyword">
      <van-cell title="历史记录"></van-cell>
      <van-cell
        v-for="(item, index) in history"
        :key="index"
        :title="item"
        @click.stop="$router.push(`/search/result?keyword=${item}`)"
      >
        <!-- stop阻止冒泡 -->
        <van-icon name="close" @click.stop="removeHistory(index)" />
      </van-cell>
      <van-cell title="单元格">
        <van-icon name="close" />
        <!-- v-html的使用 -->
        <!-- <div v-html="`<span>哈哈</span>`"></div> -->
      </van-cell>
    </van-cell-group>
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import { getSuggestion } from "@/api/search.js";
import { setItem, getItem } from "@/utils/localStorage.js";
// 以常量的格式定义一个名字，用来在localstorage中保存信息
const LOCALSTROAGE_SEARCH_NAME = "searchHistory";
export default {
  name: "Search",
  data() {
    return {
      timeOut: null, //节流开关
      keyword: "", // 搜索关键字
      suggestions: [], //搜索建议
      history: getItem(LOCALSTROAGE_SEARCH_NAME) || [] //搜索记录
    };
  },
  computed: {
    //计算高亮返回的值
    cSuggestion() {
      //1.取值
      const suggestions = this.suggestions;
      const keyword = this.keyword;
      //2.循环遍历
      let ary = [];
      suggestions.map(str => {
        //str 字符串
        //new RegExp(keyword, "gi")  == /xx/gi
        //itemStr 我们匹配到的值 xx

        const newStr = str.replace(new RegExp(keyword, "gi"), function(
          itemStr
        ) {
          //itemStr 我们匹配后的值
          return `<span style="color:red">${itemStr}</span>`;
        });
        //替换 把结果给ary
        ary.push(newStr);
      });
      return ary; //记得要return出去，把结果返回给计算属性
    }
  },
  methods: {
    //删除历史记录
    removeHistory(idx) {
      this.history.splice(idx, 1);
      setItem(LOCALSTROAGE_SEARCH_NAME, this.history);
    },
    //添加搜索记录的函数 注意去重
    addHistory(str) {
      //数组去重
      const idx = this.history.findIndex(strs => strs === str);
      if (idx > -1) {
        this.history.splice(idx, 1); //找到重复的删除
      }
      //添加到最前面
      this.history.unshift(str);
      //一切完成之后我们添加历史记录到本地
      setItem(LOCALSTROAGE_SEARCH_NAME, this.history);
      this.$router.push({
        path: "/search/result",
        query: {
          keyword: str
        }
      });
    },
    Hsuggestion(idx) {
      //...其他的功能
      //添加搜索记录
      const suggestions = this.suggestions;
      const sugword = suggestions[idx]; //联想建议的字符
      this.addHistory(sugword);
    },
    Hsearch() {
      this.addHistory(this.keyword);
    },
    onSearch() {
      // console.log(this.keyword, "搜索关键词");
      this.addHistory(this.keyword);
    },
    //获得联想建议
    async hGetSuggestion() {
      const keyword = this.keyword;
      try {
        if (!keyword) {
          this.suggestions = [];
          return;
        }
        const res = await getSuggestion(keyword);
        // console.log(res);
        this.suggestions = res.data.data.options;
      } catch (error) {
        console.log(error);
      }
    },
    //节流
    jieliu() {
      //定时器
      //1.当timeOut=null  说明我们这时候没有事件触发 是等待状态
      let timeOut = this.timeOut;
      //这个时候 timeOut 存在说明我们有事件在执行 我们就不再重复执行
      if (timeOut) {
        return;
      }
      //2. timeOut = setTimeOut(()=>{},1000);  timeOut=14;
      this.timeOut = setTimeout(() => {
        this.timeOut = null;
        //执行我们想要的函数
        this.hGetSuggestion();
      }, 2000);
      //3. timeOut=14;  timeOut != null 进去
      //4.setTimeOut 里面 timeOut = null
      //当你设定一个时间之后，函数执行的时间段就是这个时间
    },
    //防抖
    fangdou() {
      let timeOut = this.timeOut;
      if (timeOut) {
        //区别
        clearTimeout(this.timeOut);
      }
      this.timeOut = setTimeout(() => {
        //执行我们想要的函数
        this.hGetSuggestion();
      }, 2000);
    }
  }
};
</script>

<style lang="" scoped></style>
